
#define THRESHOLD 13

#define A 0  // sensor pin from IR A
#define B 1  // sensor pin from IR B
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0, ps=0;  // variable to store the value coming from the sensor
int tog=0, paused=0;
int valA,valB,preA,preB;
unsigned long pm=0;
unsigned long t1=0,t2=0,t3=0;
float rpm=0;
char enc[10];

void setup() {
  
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin, OUTPUT);
  pinMode(A,INPUT);
  pinMode(B,INPUT);  
  Serial.begin(9600);
}

void showScale(unsigned long s) {
  int i,x;
  x = s/5;
  for(i=0;i<x;i++) Serial.print("#");
  Serial.print(">");
  Serial.print(s);
  Serial.print(" RPM\n");
}
/*
 RPM = 60x1000/(48t)
 where t = time require to move one gear of rotary encoder
 there are 48 gears of rotary encoder
 */
void loop() {
  // read the value from the sensor:
  //  sensorValue = analogRead(sensorPin);
  //  delay(2); //try debounce
  //Serial.println(sensorValue);  
  //  valA = digitalRead(A);
  //  valB = digitalRead(B);
  valA = analogRead(A); 
  delay(2);
  valB = analogRead(B); 
  //delay(1);
  if( (abs(preA-valA)<THRESHOLD) && (abs(preB-valB)<THRESHOLD )) {
    // no movement but record the time
    //    t1=millis();
    paused = 1;
  } 
  else {
    //sprintf(enc,"(%d,%d), ", valA/100, valB/100);
    //    Serial.println(enc);
    if(paused!=0
    ) {
      t2=millis();
      t3=t2-t1;

      t1=millis();
      rpm=60000/(48*t3);
      //      Serial.print(rpm);
      //      Serial.println(" RPM");
      showScale(rpm);
    }
    else {
      paused=0;
      t1=millis();
    }
  }
  preA=valA;
  preB=valB;
}
